import com.mysql.cj.xdevapi.SelectStatementImpl;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo01_DriverManager {
    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet =null;
        try {
            //1.加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");//通过完全限定名加载指定的类到Java虚拟机里
            //2.获取数据库连接
            connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8" +
                    "&allowPublicKeyRetrieval=true&useSSL=false","root","123456");
            //3.创建操作命令（Statement）
           statement= connection.createStatement();
           //4.定义并执行SQL语句
            System.out.println("请输入学生姓名");
            Scanner scanner=new Scanner(System.in);
            String name=scanner.nextLine();
            String sql="select student_id,sn,sname,mail,class_id from student where name='"+name+"'";
            //5.获取查询结果集
            resultSet = statement.executeQuery(sql);//执行sql操作
            //statement.executeUpdate(sql);//更新操作（update、delete、insert）
            //6.对结果集进行遍历，获取数据
            //如果下一条有记录则返回true
            while (resultSet.next()){
                //bigint==long=8bytes
                long student_id = resultSet.getLong(1);
                String sn = resultSet.getString(2);
                String sname = resultSet.getString(3);
                String mail = resultSet.getString(4);
                long class_id = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0}，，学号={1}，学生姓名={2}，邮箱={3}，班级编号={4}",student_id,sn,sname,mail,class_id));
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //依次释放资源，关闭连接
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

}
